package com.shexianyu.simple;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * 506. 相对名次
 * 输入：score = [10,3,8,9,4]
 * 输出：["Gold Medal","5","Bronze Medal","Silver Medal","4"]
 */
public class FindRelativeRanks {
    public String[] findRelativeRanks(int[] score) {
        int n = score.length;
        String[] res = new String[n];
        //使用map集合记录原始数组值及索引
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < n; i++) {
            map.put(score[i], i);
        }
        //将score数组升序排序
        Arrays.sort(score);

        //初始排名值
        int count = 1;
        //按从高到低的顺序获取原始数组的索引，并进行排名
        for (int i = score.length - 1; i >= 0; i--) {
            if (map.containsKey(score[i])) {
                Integer integer = map.get(score[i]);
                res[integer] = count++ + "";
            }
        }
        //替换res数组中的1 2 3
        for (int i = 0; i < res.length; i++) {
            if (res[i].equals("1")) {
                res[i] = "Gold Medal";
            } else if (res[i].equals("2")) {
                res[i] = "Silver Medal";
            } else if (res[i].equals("3")) {
                res[i] = "Bronze Medal";
            }
        }
        return res;
    }

    /**
     * 官方题解
     *
     * @param score
     * @return
     */
    public String[] findRelativeRanks1(int[] score) {
        int n = score.length;
        String[] desc = {"Gold Medal", "Silver Medal", "Bronze Medal"};
        int[][] arr = new int[n][2];

        for (int i = 0; i < n; ++i) {
            arr[i][0] = score[i];
            arr[i][1] = i;
        }
        Arrays.sort(arr, (a, b) -> b[0] - a[0]);
        String[] ans = new String[n];
        for (int i = 0; i < n; ++i) {
            if (i >= 3) {
                ans[arr[i][1]] = Integer.toString(i + 1);
            } else {
                ans[arr[i][1]] = desc[i];
            }
        }
        return ans;
    }
}
